package com.xinchao.ck_mips.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.xinchao.devicemanage.constant.DeviceConstant;
import com.xinchao.devicemanage.util.DeviceInfoUtil;
import com.xinchao.devicemanage.util.UpdateTools;
import com.xinchao.machine.digital_advertise.IBaseMachine;
import com.xinchao.machine.digital_advertise.base.Allwinner;
import com.xinchao.machine.digital_advertise.tools.SharedPreferencesHelper;
import com.xinchao.machine.digital_advertise.tools.SwitchTools;

import java.lang.ref.WeakReference;
import java.util.Calendar;

/*
 *Created by xiaoqiang on 2019/1/14.
 */
public class CheckOnOffUtil {

    public static final String TAG = "CheckOnOffUtil";
    private WeakReference<Context> mContextWeakReference;
    private WeakReference<IBaseMachine> machineWeakReference;
    private static CheckOnOffUtil checkOnOffUtil;

    private Handler mHandler;
    //显示倒计时
    private Toast mToast;
    //是否开启检查非开关机时间自动关机
    private boolean isCheckOnOff = true;
    //是否显示倒计时
    private boolean isShowMsg = true;
    //倒计时，关机
    public static final int MAX_TIME = 5 * 60;
    //倒计时，显示
    public static final int SHOW_TIME = 5;
    //倒计时
    private int surplusTime;
    //非开机时间判断减少分钟数
    protected static final int START_THE_MACHINE_AHEAD_OF_TIME = 10;

    private CheckOnOffUtil(Context context, IBaseMachine iBaseMachine) {
        mContextWeakReference = new WeakReference<>(context);
        machineWeakReference = new WeakReference<>(iBaseMachine);
    }

    public static CheckOnOffUtil getInstence(Context context, IBaseMachine iBaseMachine) {
        if (checkOnOffUtil == null) {
            synchronized (UpdateTools.class) {
                if (checkOnOffUtil == null) {
                    checkOnOffUtil = new CheckOnOffUtil(context, iBaseMachine);
                }
            }
        }
        return checkOnOffUtil;
    }

    public static CheckOnOffUtil getInstence() {
        return checkOnOffUtil;
    }


    /**
     * 检查非开关机时间内倒计时关机
     *
     * @param toastMsg
     */
    public void checkOnOffTime(final String toastMsg) {

        if (!isCheckOnOff) {
            removeAllCallBack();
            return;
        }
        int[] on_off = DeviceInfoUtil.getInstance(getContext()).getDeviceOnOff();
        // return -3 不支持 -2 无效的开关机时间 -1 设置失败[开机时间晚于关机时间] 0 清除开关机时间 1 设置成功
        if (SwitchTools.getInstance(getContext()).isWrongOnOffTime(on_off[0], on_off[1], on_off[2], on_off[3])) {
            return;//无效的开关机时间
        }
        if (SwitchTools.getInstance(getContext()).isOnOffTimeSame(on_off[0], on_off[1], on_off[2], on_off[3])) {
            getIBaseMachine().setSwitchStatus(false);
            removeAllCallBack();
            return;//清除开关机时间
        }
//        if (SwitchTools.getInstance(getContext()).isOnTimeAfterOffTime(on_off[0], on_off[1], on_off[2], on_off[3])) {
//            return;//开机时间晚于关机时间
//        }

        if (!SwitchTools.getInstance(getContext()).getSwitchStatus()) {
            final int on_h = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("on_h", DeviceConstant.DEFAULT_ON_OFF[0]);
            final int on_m = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("on_m", DeviceConstant.DEFAULT_ON_OFF[1]);
            final int off_h = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("off_h", DeviceConstant.DEFAULT_ON_OFF[2]);
            final int off_m = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("off_m", DeviceConstant.DEFAULT_ON_OFF[3]);

            if (on_h == 0 && on_m == 0 && off_h == 0 && off_m == 0) {
                removeAllCallBack();
                return;
            } else {

                if (isValidOnOffTime(on_h, on_m, off_h, off_m)) {
                    Logger.t(TAG).d("isValidOnOffTime:true");
                    removeAllCallBack();
                    return;
                }
                if (mHandler != null) {
                    return;
                }

                /**
                 * 如果是A31s机型不显示倒计时提示
                 */
                if (getIBaseMachine() instanceof Allwinner) {
                    isShowMsg = false;
                }
                final boolean showToast = isShowMsg;

                mHandler = new Handler(Looper.getMainLooper());
                surplusTime = MAX_TIME;
                shutDown(false);
                Logger.t(TAG).d("开始倒计时关机");
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (showToast && mToast != null) {
                            mToast = null;
                        }

                        surplusTime--;
                        if (showToast && (MAX_TIME - surplusTime) <= SHOW_TIME) {
                            mToast = Toast.makeText(getContext(), "非正常时间开机，系统会在5分钟后自动关机", Toast.LENGTH_LONG);
                            mToast.setGravity(Gravity.CENTER,0,0);
                             //  mToast = MyToast.message(getContext(), (TextUtils.isEmpty(toastMsg) ? "非正常时间开机，系统会在5分钟后自动关机" : toastMsg));
                            //只显示SHOW_TIME秒，后取消显示
                            if ((MAX_TIME - surplusTime) == SHOW_TIME) {
                                mToast.cancel();
                                mToast = null;
                            }
                        }
                        if (surplusTime <= 0) {
                            Logger.t(TAG).d("非开关机时间倒计时结束");
                            removeAllCallBack();
                            shutDown(true);
                            if (!(getIBaseMachine() instanceof Allwinner)) {
                                getIBaseMachine().power_off();
                            }
                        } else {
                            if (showToast && mToast != null && (MAX_TIME - surplusTime) <= SHOW_TIME) {
                                mToast.show();
                            }
                            mHandler.postDelayed(this, 1000);
                        }
                    }
                }, 1000);
            }
        } else {
            removeAllCallBack();
        }
    }

    /**
     * 清除倒计时关机
     */
    private void removeAllCallBack() {
        if (mHandler != null) {
            Logger.t(TAG).d("取消倒计时关机");
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
            if (mToast != null) {
                mToast.cancel();
                mToast = null;
            }
        }
    }

    /**
     * 标准设备重置开关机时间
     *
     * @param isEnd 是否需要延迟
     */
    protected void shutDown(boolean isEnd) {
        int on_h = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("on_h", DeviceConstant.DEFAULT_ON_OFF[0]);
        int on_m = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("on_m", DeviceConstant.DEFAULT_ON_OFF[1]);
        int off_h = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("off_h", DeviceConstant.DEFAULT_ON_OFF[2]);
        int off_m = SharedPreferencesHelper.getInstance(getContext()).getSharedPreference("off_m", DeviceConstant.DEFAULT_ON_OFF[3]);
        SwitchTools.getInstance(getContext()).shutDown(on_h, on_m, off_h, off_m, isEnd, MAX_TIME / 60);
    }

    /**
     * 获取上下文引用
     *
     * @return
     */
    public Context getContext() {
        return mContextWeakReference.get();
    }

    public IBaseMachine getIBaseMachine() {
        return machineWeakReference.get();
    }

    protected boolean isValidOnOffTime(int on_h, int on_m, int off_h, int off_m) {
        Calendar cal_on = Calendar.getInstance();
        //部分机型在定时开机时间前开机造成无法正常开机，故时间判断提前10分钟,即设置的时间为6.30开机，那么机器如果在 6.20开机 也不会去关机了
        int dif = on_m - START_THE_MACHINE_AHEAD_OF_TIME;
        if (dif >= 0) {
            cal_on.set(Calendar.HOUR_OF_DAY, on_h);
            cal_on.set(Calendar.MINUTE, dif);
        } else {
            cal_on.set(Calendar.HOUR_OF_DAY, on_h - 1);
            cal_on.set(Calendar.MINUTE, dif + 60);
        }

        cal_on.set(Calendar.SECOND, 0);
        cal_on.set(Calendar.MILLISECOND, 0);

        Calendar cal_off = Calendar.getInstance();
        cal_off.set(Calendar.HOUR_OF_DAY, off_h);
        cal_off.set(Calendar.MINUTE, off_m);
        cal_off.set(Calendar.SECOND, 0);
        cal_off.set(Calendar.MILLISECOND, 0);

        Calendar cal_now = Calendar.getInstance();
        if (cal_on.after(cal_off)) {
            //开机时间在关机后
            return cal_now.after(cal_on) || cal_now.before(cal_off);
        } else {
            //开机时间在关机时间前
            return cal_now.after(cal_on) && cal_now.before(cal_off);
        }
    }
}
